package fun.lifepoem.event.Listener;

import fun.lifepoem.event.event.NewRegisterEvent;
import fun.lifepoem.event.service.TestService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

//@Component
//public class NewRegisterListener implements ApplicationListener<NewRegisterEvent> {
//    @Override
//    public void onApplicationEvent(NewRegisterEvent event) {
//        try {
//            TestService source = (TestService) event.getSource();
//            source.test();
//            TimeUnit.SECONDS.sleep(5);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
//        String result = event.getResult();
//        System.out.println("事件监听器:" + result);
//    }
//}
@Component
public class NewRegisterListener {

    @Bean(name = "listenerExecutor")
    private ThreadPoolTaskExecutor taskExecutor() {
        System.out.println("开始构建线程池");
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5); // 核心线程数
        executor.setMaxPoolSize(10); // 最大线程数
        executor.setQueueCapacity(20); // 队列容量
        executor.setThreadNamePrefix("MyThreadPool-"); // 线程名称前缀
        executor.initialize();
        return executor;
    }


    @Async(value = "listenerExecutor")
    @EventListener
    public void onApplicationEvent(NewRegisterEvent event) {
        try {
            TestService source = (TestService) event.getSource();
            source.test();
            TimeUnit.SECONDS.sleep(5);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        String result = event.getResult();
        System.out.println("事件监听器:" + result);
        System.out.println("执行的线程" + Thread.currentThread().getName());
    }
}